/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client.network;
import  java.io.*;
import  java.net.*;
import com.cse.p2p.common.*;
import com.cse.p2p.database.*;
import com.cse.p2p.hash.*;
import com.cse.p2p.localfile.*;
import com.cse.p2p.parser.*;
import java.util.HashMap;
import java.util.List;

/**
 *
 * @author TuyetNgan
 */
public class ClientControlTask_Server extends Thread{
        private BufferedReader inStream = null;
        private PrintStream outStream = null;
        private String fromServer, fromClient, fromScreen;
        private BufferedReader infromScreen = null;
        int defaultportDataSend = 2000;
        int defaultportDataReceive = 2001;
        private Socket clientSocket = null;
        public ClientControlTask_Server(Socket s) {
            this.clientSocket = s;
        }
        private long startTime, endTime;
        public void  newChat(){
		try{
			outStream = new PrintStream(new DataOutputStream(clientSocket.getOutputStream()));
		 	inStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            infromScreen = new BufferedReader(new InputStreamReader(System.in));
		}
		catch(IOException e){}
        }
        public void closeConnection(){
                try {
                    outStream.close();
                    inStream.close();
                    clientSocket.close();
                }
                catch (IOException e){}

        }
        @Override
        public void run() {
            try {

                infromScreen = new BufferedReader(new InputStreamReader(System.in));

                int action;
                /* Client choose action */
                System.out.println("Choose action");
                while ((fromScreen = infromScreen.readLine()) != null) {
                    if (fromScreen.equals("upfile")) {
                        action = 1;
                    } else if(fromScreen.equals("downfile")){
                        action = 2;
                    }
                    else action = 3;

                    /*Client choose file to up*/
                    // example
                    File file = new File("D://Ass1CN/sqlitejdbc-v056.jar");

                    /* communicate with server */
                    /* client send */
                    if (action == 1) {
                        FileMetadata fileMetadata = new FileMetadata("file_name", "file_desc",
                                HashImplement.getHashFile(file), file.length());
                        Message m = new Message("GET", "UP", fileMetadata.toString());
                        outStream.println(m);
                    }
                    else if(action == 2){
                        System.out.println("Choose dicfile");
                        String pathDicFile = infromScreen.readLine();
                        String contentDicFile = LocalFile.getContentDicFile(pathDicFile);
                        DicFile dicFile = DicFile.parseDicFileFromXML(contentDicFile);
                        Message m = new Message("GET","LIST", Integer.toString(dicFile.getFileID()));
                        outStream.println(m.toString());
                    }
                    else {}

                    /* waiting for server */
                    String mess;
                    Message message;
                    String data;
                    boolean flagbreak = false;
                    while ((mess = inStream.readLine()) != null) {

                        message = Message.fromString(mess);
                        int typeOfProtocol = message.getType();
                        data = message.getData();

                        switch (typeOfProtocol) {
                            //need Info from file ?!!
                            //case for info to call waitingState or downloadState

                            //server response the info of all available pieces of a file
                            case Message.MsgType.RES_FOR_AVAI_PIECES: {
                                // original fileID before request server
                                int fileID = 1; //example

                                List<PeerInfo> info = PeerInfo.listFromString(data);
                                /* Call Database to know which piece client need */


                                /* Client calculate to choose suitable peer and piece */
                                String[] peerChosen = client.logic.ClientLogicImplement.findPieceAndPeer(info, Integer.toString(fileID));
                                Message newMess = new Message(peerChosen[0], peerChosen[1], peerChosen[2]);

                                /* return peer want to download piece*/
                                newMess.toString();

                                break;
                            }
                            //server collect the info of all available pieces of a file from one peer
                            case Message.MsgType.REQ_VRF_ALL_PIECES: {
                                int fileID = Integer.parseInt(data);

                                /* search in DB to get peer info */


                                //                            int[] pieces = new int[];
                                //                            getPiecesExist(fileID);
                                //                            PeerInfo info = new PeerInfo(0, pieces, data);
                                //                            String peerInfo = info.toString();

                                /* return <peerInfo> to server */
                                break;
                            }

                            //server response for the uploading request
                            case Message.MsgType.RES_FILE_TRANSFER: {
                                System.out.println("Server allow to up file");
                                if (data.equals("OK")) {
//                                    Thread t = new Thread(new SendTask(file, this.clientSocket.getRemoteSocketAddress().toString()));
//                                    t.sleep(1000);
//                                    t.start();
//                                    //estimate time
//                                    startTime = System.currentTimeMillis();
//                                    while (t.isAlive());

                                } else if (data.equals("NONE")) {
                                    System.out.println("Server not allow upfile!");
                                    flagbreak = true;
                                } else { // error
                                    System.out.println("Error: RES_FILE_TRANSFER");
                                }
                                break;
                            }

                            //server request for the dicfile transfering
                            case Message.MsgType.REQ_UP_DIC_FILE: {
                                endTime = System.currentTimeMillis();

                                System.out.println("Server request for Dicfile transfer ");
                                /* remeber file upload finished */
                                // TO DO : checkin DB

                                /* reponse message OK */
                                Message messSend = new Message("PUT", "UP", "OK");
                                outStream.println(messSend.toString());
                                /* check path to write Dicfile into Disk */
                                File file_dic_received = new File("C://client/file_dic_received.txt");
                                file_dic_received.createNewFile();
                                /* thread prepare to receive Dicfile */
//                              Thread t = new Thread(new ReceiveTask(file_dic_received));
//                                t.start();
//                                while (t.isAlive());

                                /* reponse message Finish  */
                                Message messSend2 = new Message("PUT", "OK", "OK");
                                outStream.println(messSend2.toString());
                                break;
                            }
                        }
                        if (flagbreak) {
                            break;
                        }
                    }
                }
            } catch (Exception ex) {
            }

        }
    
}
